﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using DreamWork.Web.API.Infrastructure;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Swashbuckle.AspNetCore.Swagger;

namespace dreamwork.auth.api
{
	public class Startup
	{
		public Startup(IConfiguration configuration)
		{
			Configuration = configuration;
		}

		public IConfiguration Configuration { get; }

		// This method gets called by the runtime. Use this method to add services to the container.
		public IServiceProvider ConfigureServices(IServiceCollection services)
		{

			#region JWT Authentication
			services.AddAuthentication(x=> {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
			.AddJwtBearer(options =>
			  {
				  options.TokenValidationParameters = new TokenValidationParameters
				  {
					  ValidateIssuer = true,
					  ValidateAudience = true,
					  ValidateLifetime = true,
					  ValidateIssuerSigningKey = true,
					  ValidIssuer = Configuration["Jwt:Issuer"],
					  ValidAudience = Configuration["Jwt:Audience"],
					  IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
				  };
                  options.IncludeErrorDetails = true;
			  });

			#endregion
			services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest).AddControllersAsServices();

			#region Service

			services.AddTransient<ITokenService, TokenService>();
			#endregion

			#region Swagger
			services.AddSwaggerGen(options =>
			{
				options.DescribeAllEnumsAsStrings();
				options.SwaggerDoc("v1", new Info { Title = "Dreamwork Auth API", Version = "v1" });
				options.OperationFilter<HttpAuthHeaderFilter>();
			});
			#endregion

			#region Cors
			services.AddCors(options =>
			{
				options.AddPolicy("CorsPolicy",
					builder => builder.AllowAnyOrigin()
					.AllowAnyMethod()
					.AllowAnyHeader()
					.AllowCredentials());
			});
			#endregion

			#region configure autofac

			var container = new ContainerBuilder();
			container.Populate(services);
			return new AutofacServiceProvider(container.Build());
			#endregion

		}

		// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
		public void Configure(IApplicationBuilder app, IHostingEnvironment env)
		{
			if (env.IsDevelopment())
			{
				app.UseDeveloperExceptionPage();
			}
			else
			{
				app.UseHsts();
			}

			app.UseMvc();
			app.UseCors("CorsPolicy");
			app.UseSwagger();
			app.UseAuthentication();
			app.UseHttpsRedirection();
			app.UseMvcWithDefaultRoute();
			app.UseStaticFiles();
			app.UseSwagger()
			   .UseSwaggerUI(c =>
			   {
				   c.SwaggerEndpoint("/swagger/v1/swagger.json", "Dreamwork.Auth.API");
			   });
		}
	}
}
